package com.qyhl.school.school.reporter;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.school.school.SchoolHomeActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolContributionBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolReporterActBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolReporterHomeBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.androidx.XBanner;
import com.stx.xhb.androidx.transformers.Transformer;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SchoolReporterFragment extends BaseFragment implements SchoolReporterContract.SchoolReporterView {
    @BindView(R2.id.banner)
    XBanner banner;
    @BindView(R2.id.select_recyclerview)
    RecyclerView selectRecyclerview;
    @BindView(R2.id.select_layout)
    LinearLayout selectLayout;
    @BindView(R2.id.article_recyclerview)
    RecyclerView articleRecyclerview;
    @BindView(R2.id.article_layout)
    LinearLayout articleLayout;
    @BindView(R2.id.action_recyclerview)
    RecyclerView actionRecyclerview;
    @BindView(R2.id.action_layout)
    LinearLayout actionLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.divider)
    View divider;
    @BindView(R2.id.divider2)
    View divider2;

    private SchoolReporterPresenter mPresenter;

    private boolean hasPicture;//是否是无图

    private SchoolReporterHomeBean mBean;

    private List<NewsBean> bannerList = new ArrayList<>();

    private CommonAdapter<SchoolReporterActBean> actCommonAdapter;
    private List<SchoolReporterActBean> actList = new ArrayList<>();

    private CommonAdapter<SchoolContributionBean> articleCommonAdapter;
    private List<SchoolContributionBean> articleList = new ArrayList<>();

    private CommonAdapter<NewsBean> actionCommonAdapter;
    private List<NewsBean> actionList = new ArrayList<>();


    public static SchoolReporterFragment newInstance() {
        SchoolReporterFragment fragment = new SchoolReporterFragment();
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_school_reporter_home, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SchoolReporterPresenter(this);


        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setEnableLoadMore(false);

        selectRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));

        selectRecyclerview.setAdapter(actCommonAdapter = new CommonAdapter<SchoolReporterActBean>(getContext(), R.layout.item_school_reporter_act_home, actList) {
            @Override
            protected void convert(ViewHolder holder, SchoolReporterActBean bean, int i) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(SchoolReporterFragment.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getTitle());

                holder.setText(R.id.address, bean.getAddress());

                holder.setText(R.id.num, bean.getReportCount() + "个小伙伴");

                if (bean.isReportOver()) {
                    holder.setImageResource(R.id.tag, R.drawable.school_new_home_reporter_end_tag);
                } else if (bean.isReportNotStart()) {
                    holder.setImageResource(R.id.tag, R.drawable.school_new_home_reporter_forecast_tag);
                } else {
                    holder.setImageResource(R.id.tag, R.drawable.school_new_home_reporter_tag);
                }
                holder.setVisible(R.id.sign_btn, false);

                if (StringUtils.isNotEmpty(bean.getEndDate())) {
                    holder.setText(R.id.date, bean.getStartDate() + "—" + bean.getEndDate());
                } else {
                    holder.setText(R.id.date, bean.getStartDate());
                }


            }
        });

        articleRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        articleRecyclerview.setAdapter(articleCommonAdapter = new CommonAdapter<SchoolContributionBean>(getContext(), R.layout.item_school_report_catalog, articleList) {
            @Override
            protected void convert(ViewHolder holder, SchoolContributionBean newsBean, int i) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(SchoolReporterFragment.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                holder.setText(R.id.title, newsBean.getTitle());

                TextView title = holder.getView(R.id.title);
                title.setMaxLines(2);

                holder.setVisible(R.id.tagName, false);

                holder.setText(R.id.scan_num, "观看量:" + newsBean.getHitCount());

                if (StringUtils.isNotEmpty(newsBean.getWriter())) {
                    holder.setText(R.id.writer, newsBean.getWriter());
                    holder.setVisible(R.id.writer, true);
                } else {
                    holder.setVisible(R.id.writer, false);
                }
            }
        });

        actionRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        actionRecyclerview.setAdapter(actionCommonAdapter = new CommonAdapter<NewsBean>(getContext(), R.layout.item_school_report_catalog, actionList) {
            @Override
            protected void convert(ViewHolder holder, NewsBean newsBean, int i) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(SchoolReporterFragment.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                holder.setText(R.id.title, newsBean.getTitle());

                TextView title = holder.getView(R.id.title);
                title.setMaxLines(2);

                holder.setVisible(R.id.tagName, false);
                holder.setText(R.id.tagName, "#小记者在行动#");

                holder.setText(R.id.scan_num, "观看量:" + newsBean.getHitCount());

                if (StringUtils.isNotEmpty(newsBean.getWriter())) {
                    holder.setText(R.id.writer, newsBean.getWriter());
                    holder.setVisible(R.id.writer, true);
                } else {
                    holder.setVisible(R.id.writer, false);
                }

            }
        });

        mPresenter.getHome();
    }


    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getHome();
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getHome();
            }
        });


        banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner xBanner, Object o, View view, int position) {
                skip(bannerList.get(position));
            }
        });

        actCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_DETAIL)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });


        articleCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_REPORTER_CONTRIBUTION_DETAIL)
                        .withInt("id", articleList.get(i).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        actionCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                skip(actionList.get(i));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    private void skip(NewsBean bean) {
        switch (bean.getType()) {
            case "1"://普通新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
            }
            break;
            case "2"://图片新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("section", bean.getCatalogID());
                RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
            }

            break;
            case "3"://直播
            {
                Bundle bundle = new Bundle();
                bundle.putString("newsId", bean.getID());
                bundle.putString("liveType", bean.getLivetype());
                RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
            }
            break;
            case "4"://标题新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("title", bean.getTitle());
                bundle.putString("url", bean.getRedirectURL());
                RouterManager.router(ARouterPathConstant.ADV, bundle);
            }
            break;
            case "5"://视频新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
            }
            break;
            case "8"://互动直播
                break;
            case "101"://抓取新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
            }
            break;
            default:
                break;

        }
    }

    @OnClick({R2.id.back_btn, R2.id.sign_enter, R2.id.clue_enter, R2.id.publish_enter, R2.id.article_enter
            , R2.id.activity_enter, R2.id.act_more, R2.id.art_more, R2.id.move_more})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            if (getActivity() instanceof SchoolHomeActivity) {
                ((SchoolHomeActivity) getActivity()).doFinish();
            }
        } else if (id == R.id.sign_enter) {
            RouterManager.routerLoginInterceptor(getContext(), ARouterPathConstant.SCHOOL_REPORTER_SIGN);
        } else if (id == R.id.clue_enter) {
            RouterManager.router(ARouterPathConstant.SCHOOL_REPORTER_CLUE);
        } else if (id == R.id.publish_enter) {
            RouterManager.router(ARouterPathConstant.SCHOOL_REPORTER_PUBLISH);
        } else if (id == R.id.article_enter || id == R.id.art_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_CONTRIBUTION_LIST)
                    .navigation();
        } else if (id == R.id.activity_enter) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_LIST)
                    .withString("title", "活动")
                    .withString("id", mBean.getYxgjCatalogId() + "")
                    .navigation();
        } else if (id == R.id.act_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_ACT_LIST)
                    .withString("title", "优选活动")
                    .navigation();
        } else if (id == R.id.move_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_REPORTER_NEWS)
                    .withString("title", "小记者在行动")
                    .withString("id", mBean.getXjzzxdCatalogId() + "")
                    .navigation();
        }
    }

    @Override
    public void setHome(SchoolReporterHomeBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        refresh.finishRefresh();

        mBean = bean;

        if (bean.getReporterActList() != null && bean.getReporterActList().size() > 0) {
            selectLayout.setVisibility(View.VISIBLE);

            actList.clear();
            actList.addAll(bean.getReporterActList());
            actCommonAdapter.notifyDataSetChanged();
        } else {
            selectLayout.setVisibility(View.GONE);
        }

        if (bean.getXjzzxdList() != null && bean.getXjzzxdList().size() > 0) {
            actionLayout.setVisibility(View.VISIBLE);
            divider.setVisibility(View.VISIBLE);
            actionList.clear();
            actionList.addAll(bean.getXjzzxdList());
            actionCommonAdapter.notifyDataSetChanged();
        } else {
            actionLayout.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
        }

        if (bean.getYxgjList() != null && bean.getYxgjList().size() > 0) {
            articleLayout.setVisibility(View.VISIBLE);
            divider2.setVisibility(View.VISIBLE);
            articleList.clear();
            articleList.addAll(bean.getYxgjList());
            articleCommonAdapter.notifyDataSetChanged();
        } else {
            articleLayout.setVisibility(View.GONE);
            divider2.setVisibility(View.GONE);
        }

        if (bean.getCarousel() != null && bean.getCarousel().size() > 0) {
            bannerList = bean.getCarousel();
            banner.setVisibility(View.VISIBLE);

            banner.setPageTransformer(Transformer.Scale);
            banner.offsetTopAndBottom(10);
            banner.setData(R.layout.item_school_new_home_banner, mBean.getCarousel(), null);
            banner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner xBanner, Object model, View view, int i) {
                    RoundedImageView bannerCover = view.findViewById(R.id.cover);
                    Glide.with(SchoolReporterFragment.this)
                            .load(((NewsBean) model).getLogo())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                            .into(bannerCover);
                }
            });
        } else {
            banner.setVisibility(View.GONE);
        }


    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        refresh.finishRefresh();
        if (!NetUtil.isNetworkAvalible(getContext())) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }


}
